package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.pojo.Member;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    @Transactional
    @Override
    public void saveOrEdit(String telephone) {
        // 根据手机号获取会员信息
        Member member = memberDao.findByTelephone(telephone);
        if (member == null) {
            // 不是会员，自动注册
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            // 调用Service保存会员
            memberDao.add(member);
        }
    }

    @Override
    public Map<String, Object> getMemberReport() {
        List<String> months = getMonthOfLastYear();
        List<Long> memberCount = new ArrayList<>();
        //统计每个月份对应的会员数量
        for (String month : months) {
            String firstDay = month + "-01"; // 2020-01-01
            String lastDay = getThisMonthLastDay(firstDay);
            long count = memberDao.findCountBeforeByDate(lastDay);
            memberCount.add(count);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("months", months);
        map.put("memberCount", memberCount);

        return map;
    }

    /**
     * @return java.util.Map<java.lang.String   ,   java.lang.Object>
     * @Author ZhangYi
     * @Description //TODO 将区间内所有月份保存起来,并循环调用dao层查询结果
     * @Date 7:31 2020/3/10
     * @Param [starDate, endDate]
     */
    @Override
    public Map<String, Object> getReportByDate(String starDate, String endDate) {
        try {
            log.debug("getReportByDate::" + starDate + endDate);
//            调取方法获取区间内所有的月份,以yyyy-MM格式保存
            List<String> months = getMonthOfYear(starDate, endDate);
            List<Long> memberCount = new ArrayList<>();
            starDate = starDate + "-01";
            System.out.println("months::" + months);
            for (String month : months) {
                String firstDay = month + "-01"; // 2020-01-01
                String lastDay = getThisMonthLastDay(firstDay);
                long count = memberDao.findCountBetweenDate(starDate, lastDay);
                memberCount.add(count);
            }
            log.debug("months:::" + months);
            log.debug("memberCount::" + memberCount);
            Map<String, Object> map = new HashMap<>();
            map.put("months", months);
            map.put("memberCount", memberCount);
            log.debug("memberServiceImpl return map::" + map);
            return map;

        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    //    获取区间内所有月份的方法
    private List<String> getMonthOfYear(String starTime, String endTime) throws ParseException {
        log.debug("获取区间内所有月份方法::"+starTime+endTime);
        List<String> months = new ArrayList<>();
        // bug,前端传来的数据接收时减了一个月,所以起始时间不加入集合,且endTime需要加1个月
        // months.add(starTime);
        // endtime加一个月
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        Date endDate0 = simpleDateFormat.parse(endTime);
        calendar.setTime(endDate0);
        calendar.add(Calendar.MONTH, 1);
        endTime = simpleDateFormat.format(calendar.getTime());

        Date starDate = simpleDateFormat.parse(starTime);
        calendar.setTime(starDate);
        System.out.println(calendar.getTime());
        String endDate = "";
//        每循环一次起始时间涨一个月,并存入集合,直到日期与结束时间相同为止
        while (!(endTime.equals(endDate))) {
            calendar.add(Calendar.MONTH, 1);
            endDate = simpleDateFormat.format(calendar.getTime());
            months.add(endDate);
        }
        return months;
    }

    /**
     * @return java.util.Map<java.lang.String       ,       java.lang.Object>
     * @Author ZhangYi
     * @Description //TODO 统计会员男女分布比例以及年龄分布(未优化)
     * @Date 1:42 2020/3/8
     * @Param []
     */
//    @Override
//    public Map<String, Object> getMemberMessage() {
//        try {
////            1.接收dao层查询到的数据
//            List<Map<String, String>> countOfFindBySex = memberDao.findMemberCountBySex();
//            List<Map<String, String>> countOfFindByAge = memberDao.findMemberCountByAge();
////            2.将集合中的'name'存到name集合中去
//            List<String> legendNames = new ArrayList<String>();
////                    2.1遍历countOfFindByAge集合将name的值添加进去
//            for (Map<String, String> ageMap : countOfFindByAge) {
//                legendNames.add(ageMap.get("name"));
//            };
////                     2.2遍历countOfFindBySex集合将name的值添加进去
//            for (Map<String, String> ageMap : countOfFindBySex) {
//                legendNames.add(ageMap.get("name"));
//            }
////        日志记录查询到的结果
//            log.debug("ResultOfFindMemberCountByAge"+countOfFindByAge);
//            System.out.println("ResultOfFindMemberCountByAge::"+countOfFindByAge);
//            System.out.println("ResultOfFindMemberCountBySex::"+countOfFindBySex);
//            Map<String,Object> map = new HashMap<String,Object>();
//            map.put("legendname",legendNames);
//            map.put("age",countOfFindByAge);
//            map.put("sex",countOfFindBySex);
//            System.out.println("ResultMap::"+map);
//            return map;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * @return java.util.List<java.util.Map   <   java.lang.String   ,   java.lang.String>>
     * @Author ZhangYi
     * @Description //TODO 调用dao层来获取会员的性别分布信息
     * @Date 3:35 2020/3/9
     * @Param []
     */
    @Override
    public List<Map<String, String>> getMemberCountBySex() {
        try {
            log.debug("STAR METHOD findMemberCountBySex()");
//            调用dao层来获取会员的性别分布信息
            List<Map<String, String>> memberCountOfFindBySex = memberDao.findMemberCountBySex();
            log.debug("memberCountOfFindBySex::" + memberCountOfFindBySex);
            return memberCountOfFindBySex;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * @return java.util.List<java.util.Map   <   java.lang.String   ,   java.lang.String>>
     * @Author ZhangYi
     * @Description //TODO 调用dao层来获取会员的年龄分布信息
     * @Date 3:39 2020/3/9
     * @Param []
     */
    @Override
    public List<Map<String, String>> getMemberCountByAge() {
        try {
            log.debug("STAR METHOD findMemberCountByAge()");
//            调用dao层来获取会员的年龄分布信息
            List<Map<String, String>> memberCountOfFindByAge = memberDao.findMemberCountByAge();
            log.debug("memberCountOfFindBySex::" + memberCountOfFindByAge);
            return memberCountOfFindByAge;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    private String getThisMonthLastDay(String firstDay) {
        //2020-02-01 thisMonthFirstDay
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date firstDate = sdf.parse(firstDay);
            //创建日历对象
            Calendar cal = Calendar.getInstance();
            //设置为本月一号
            cal.setTime(firstDate);
            //调整为下月1号
            cal.add(Calendar.MONTH, 1);
            //调整为前一天(本月的最后一天)
            cal.add(Calendar.DAY_OF_MONTH, -1);

            String str = sdf.format(cal.getTime());
            return str;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取最近一年的月份
     *
     * @return
     */
    private List<String> getMonthOfLastYear() {
        List<String> months = new ArrayList<>();
        //获取前12个月份
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -12);
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
            String date = simpleDateFormat.format(calendar.getTime());
            months.add(date);
        }
        return months;
    }
}